package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 配置登录过滤的过滤器
 */
@WebFilter("/*")
@Slf4j
public class LogCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("过滤器开始工作");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取当前请求的uri地址
        String uri = request.getRequestURI();
        log.info("本次请求的路径为"+uri);

        //将获取到的路径与配置的路径对比
        boolean result = matchUrl(uri);
        if(result){
            //如果比对结果在配置路径中,放行
            filterChain.doFilter(request,response);
            return;
        }

        if(request.getSession().getAttribute("user") != null){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));

            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request,response);
            return;
        }

        //获取请求中,session名为employee的值
        Long id = (Long) request.getSession().getAttribute("employee");
        if(id == null){
            //若为null,说明不存在该session,返回没有登录
            response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
            return;
        }

        BaseContext.setCurrentId(id);

        filterChain.doFilter(request,response);

    }

    /**
     * 比对路径的方法
     * @param uri
     * @return
     */
    private boolean matchUrl(String uri) {
        //配置需要放行的地址【静态资源全部放 + 登录和退出的】
        String[] loginUrls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg",
        "/order/export"};

        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String loginUrl : loginUrls) {
            boolean match = antPathMatcher.match(loginUrl, uri);
            if(match){
                return true;
            }
        }
        return false;
    }
}
